import { Module } from '@nestjs/common';
import { ConfigService, ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        console.log(configService.get('DB_HOST'), `configService.get('DB_HOST')`);
        return {
          type: 'mysql',
          host: configService.get('DB_HOST'),
          port: configService.get('DB_PORT'),
          username: configService.get('DB_USERNAME'),
          password: configService.get('DB_PASSWORD'),
          database: configService.get('DB_DATABASE'),
          synchronize: false,
          // 解决通过 pnpm migration:run 初始化数据时，遇到的 SET FOREIGN_KEY_CHECKS = 0; 等语句报错问题, 仅在执行数据迁移操作时设为 true
          multipleStatements: false,
          entities: ['dist/modules/**/*.entity{.ts,.js}'],
          migrations: ['dist/migrations/*{.ts,.js}'],
          subscribers: ['dist/modules/**/*.subscriber{.ts,.js}'],
          autoLoadEntities: true
        };
      }
      // dataSourceFactory: async (options: IDatabaseConfig) => {
      //   const dataSource = await new DataSource(options).initialize();
      //   return dataSource;
      // }
    })
  ],
  providers: [],
  exports: []
})
export class DatabaseModule {}
